# -*- coding: utf-8 -*-

import pymysql
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.utils.project import get_project_settings


class ViewspotcommentsPipeline(object):
    def __init__(self):
        # reload(sys)
        # sys.setdefaultencoding('utf-8')
        settings = get_project_settings()
        self.connection = pymysql.connect(
            host=settings['MYSQL_HOST'],  # 读取settings中的配置
            database=settings['MYSQL_DBNAME'],
            user=settings['MYSQL_USER'],
            password=settings['MYSQL_PASSWD'],
            port=settings['MYSQL_PORT'],
            charset='utf8',
            # cursorclass=psycopg2.cursor().DictCursor,
            # use_unicode=False,
        )
        self.cursor = self.connection.cursor()

    def process_item(self, item, spider):
        try:
            if item.get('view_name'):
                self.cursor.execute(
                    'insert into cr_xiech_estimate_ss_comments(view_name,username,view_star,sight_score,interest_score,costperformance_score,comment,travel_time,comment_time,usefultodo,detail_url) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',
                    (
                    item['view_name'], item['username'], item['view_star'], item['sight_score'], item['interest_score'],
                    item['costperformance_score'], item['comment'], item['travel_time'], item['comment_time'],
                    item['usefultodo'], item['detail_url']))
                self.connection.commit()
        except Exception as e:
            self.connection.rollback()
            print("Error: %s" % e)
        return item
